const user = require('../models/userDetail')
const pointprocess = require('../models/pointProcess')
const menu = require('../models/menu')
const point = require('../models/point')

var express = require('express');
var async = require('async');  //async module
var router = express.Router();

const formidable = require('formidable');

router.post('/', (req, res, next)=>{
    var form = new formidable.IncomingForm();
    let nowTime = new Date();
    let Return_data = [];
    form.parse(req, function(err, fields, files){
        if(err){
            res.json({'state': false});
        }else{
            user.find({
                stuNo: fields.stuNo,
                school: fields.school
            }, (err, student)=>{
                if(err){
                    res.json({'state': false, 'msg' : 'The student is not exist!'});
                }else{
                    if(student.length===0){
                        res.json({'state':false, 'msg': 'The student is not exist!'});
                    }else{
                        if(fields.time === "0") {
                            nowTime.setDate(nowTime.getDate()-7);
                            nowTime.setHours(0,0,0,0);
                        }else if(fields.time === "1"){
                            nowTime.setMonth(nowTime.getMonth()-3);
                            nowTime.setHours(0,0,0,0);
                        }else {
                            nowTime.setFullYear(2010);
                        }
                        // console.log("nowTime:" + new Date(nowTime));
                        pageQueryNew(fields.page, fields.count, pointprocess, {UUID: student[0].UUID, time: {$gt: nowTime}}, {time: fields.reverse}, async (err, result) => {
                            if(err){
                                res.json({'state': false, 'msg': 'the process is not exist!'})
                            }else{
                                var formatDate = function (date) {
                                    var y = date.getFullYear();
                                    var m = date.getMonth() + 1;
                                    m = m < 10 ? ('0' + m) : m;
                                    var d = date.getDate();
                                    d = d < 10 ? ('0' + d) : d;
                                    var h = date.getHours();
                                    h=h < 10 ? ('0' + h) : h;
                                    var minute = date.getMinutes();
                                    minute = minute < 10 ? ('0' + minute) : minute;
                                    var second=date.getSeconds();
                                    second=second < 10 ? ('0' + second) : second;
                                    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
                                }
                                var find_Menu = function (les_info){
                                    return new Promise((resolve, reject)=>{
                                        menu.find({lesson: les_info[0]}, (err, lesson)=>{
                                            if(err){
                                                res.json({'statee':false, 'msg':'the lesson is not exist!'});
                                            }else{
                                                if(lesson === "undefined" || lesson.length===0){
                                                    resolve({
                                                        charName : "章节不存在",
                                                        charSubName : "章节不存在"
                                                    });
                                                }else{
                                                    resolve({
                                                        charName : lesson[0].menu[les_info[1]].title,
                                                        charSubName : lesson[0].menu[les_info[1]].subtitle[les_info[2]]
                                                    });
                                                }
                                            }
                                        });
                                    })
                                }
                                var find_Point = function (charInfo, pointId){
                                    return new Promise((resolve, reject)=>{
                                        point.find({_id:pointId}, (err, pointInfo)=>{
                                            if(err){
                                                res.json({'state': false, 'msg':'the point is not exist!'});
                                            }else{
                                                if(pointInfo === "undefined" || pointInfo.length===0){
                                                    resolve({
                                                        charInfo,
                                                        pointName: "知识点不存在"
                                                    });
                                                }else{
                                                    resolve({
                                                        charInfo,
                                                        pointName: pointInfo[0].title
                                                    });
                                                }
                                            }
                                        });
                                    })
                                }
                                const {data: Process, count} = result
                                // console.log("number: " + Process.length);
                                // console.log(Process)
                                for(var i=0;i<Process.length;i++){
                                    if(i===Process.length-1 || (Math.abs(Process[i+1].time - Process[i].time)>3000)){
                                        let return_data = {};
                                        let les_info = Process[i].menu.split(',');
                                        let char_name = {};
                                        let point_name = {};
                                        char_name = await find_Menu(les_info).then();
                                        point_name = await find_Point(char_name, Process[i].pointId).then();
                                        return_data.charName = point_name.charInfo.charName;
                                        return_data.charSubName = point_name.charInfo.charSubName;
                                        return_data.pointName = point_name.pointName;
                                        return_data.pointId = Process[i].pointId;
                                        return_data.view = Process[i].view;
                                        if(les_info[0]==='wx'){
                                            return_data.lesName = '微信小程序';
                                        }else if(les_info[0]==='js'){
                                            return_data.lesName = 'JaveScript';
                                        }else if(les_info[0]==='ydhlw'){
                                            return_data.lesName = '移动互联网';
                                        }
                                        let date = new Date(Process[i].time + (8*60*60*1000));
                                        // console.log(date);
                                        return_data.time = formatDate(date);
                                        Return_data.push(return_data);
                                    }
                                }
                                // console.log(Return_data)
                                res.json({'state': true, 'msg': Return_data});
                            }
                        })
                    } 
                }   
            })
        }
    });
});

module.exports = router;


/**

* 分页查询，该方法依赖`mongoose`组件

* @param page 页数，如第1页，就传1

* @param pageSize 每页大小，如一页展示10条，就传10

* @param Model mongoose的指定Model对象，是一个schema对象

* @param fieldJson 查询字段

* @param populate 关联查询

* @param queryParams 查询条件

* @param sortParams 排序

* @param callback 回调函数

*/

function pageQueryNew(page, pageSize, Model,  queryParams, sortParams, callback) {

    var start = (page -1) * pageSize;

    var $page = {};

    async.parallel(
        {

            count:function (done) {// 查询数量

                Model.count(queryParams).exec(function (err, count) {

                    done(err, count);

                });

            },

            records:function (done) {   // 查询一页的记录

                Model.find(queryParams).skip(start).sort(sortParams).limit(pageSize).exec(function (err, doc) {

                    done(err, doc);

                });

            }

        }, function (err, results) {

            var count = results.count;

            $page.total = count;

            $page.data = results.records;

            callback(err, $page);

        }
    );

}